<!-- Licensed under a BSD license. See license.html for license -->
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  <title>WebGL - Textures - Skybox and Environment Map</title>
  <link type="text/css" href="../../resources/webgl-tutorials.css" rel="stylesheet" />
</head>

<body>
  <div id="info">
    <div class="description">
      Skybox using a cubemap.<br />
    </div>
    <a href="https://webglfundamentals.org/webgl/lessons/zh_cn/webgl-skybox.html" target="_blank">WebGL -
      天空盒</a>
  </div>
  <canvas id="canvas"></canvas>
</body>
<script id="envmap-vertex-shader" type="x-shader/x-vertex">
attribute vec4 a_position;
attribute vec3 a_normal;

uniform mat4 u_projection;
uniform mat4 u_view;
uniform mat4 u_world;

varying vec3 v_worldPosition;
varying vec3 v_worldNormal;

void main() {
  // Multiply the position by the matrix.
  gl_Position = u_projection * u_view * u_world * a_position;

  // send the view position to the fragment shader
  v_worldPosition = (u_world * a_position).xyz;

  // orient the normals and pass to the fragment shader
  v_worldNormal = mat3(u_world) * a_normal;
}
</script>
<!-- fragment shader -->
<script id="envmap-fragment-shader" type="x-shader/x-fragment">
precision highp float;

// Passed in from the vertex shader.
varying vec3 v_worldPosition;
varying vec3 v_worldNormal;

// The texture.
uniform samplerCube u_texture;

// The position of the camera
uniform vec3 u_worldCameraPosition;

void main() {
  vec3 worldNormal = normalize(v_worldNormal);
  vec3 eyeToSurfaceDir = normalize(v_worldPosition - u_worldCameraPosition);
  vec3 direction = reflect(eyeToSurfaceDir,worldNormal);

  gl_FragColor = textureCube(u_texture, direction);
}
</script>
<script id="skybox-vertex-shader" type="x-shader/x-vertex">
attribute vec4 a_position;
varying vec4 v_position;
void main() {
  v_position = a_position;
  gl_Position = a_position;
}
</script>
<script id="skybox-fragment-shader" type="x-shader/x-fragment">
precision mediump float;

uniform samplerCube u_skybox;
uniform mat4 u_viewDirectionProjectionInverse;

varying vec4 v_position;
void main() {
  vec4 t = u_viewDirectionProjectionInverse * v_position;
  gl_FragColor = textureCube(u_skybox, normalize(t.xyz / t.w));
}
</script>
<!--
for most samples webgl-utils only provides shader compiling/linking and
canvas resizing because why clutter the examples with code that's the same in every sample.
See http://webglfundamentals.org/webgl/lessons/webgl-boilerplate.html
and http://webglfundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html
for webgl-utils, m3, m4, and webgl-lessons-ui.
-->
<script src="../../resources/webgl-utils.js"></script>
<script src="../../resources/m4.js"></script>
<script src="../../resources/primitives.js"></script>
<script>
  "use strict";

  function main() {
    // Get A WebGL context
    /** @type {HTMLCanvasElement} */
    var canvas = document.getElementById("canvas");
    var gl = canvas.getContext("webgl");
    if (!gl) {
      return;
    }

    // setup GLSL programs and lookup locations
    const envmapProgramInfo = webglUtils.createProgramInfo(
      gl, ["envmap-vertex-shader", "envmap-fragment-shader"]);
    const skyboxProgramInfo = webglUtils.createProgramInfo(
      gl, ["skybox-vertex-shader", "skybox-fragment-shader"]);

    // create buffers and fill with vertex data
    const cubeBufferInfo = primitives.createCubeBufferInfo(gl, 1);
    const quadBufferInfo = primitives.createXYQuadBufferInfo(gl);

    // Create a texture.
    const texture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);

    const faceInfos = [
      {
        target: gl.TEXTURE_CUBE_MAP_POSITIVE_X,
        url: '../../resources/images/computer-history-museum/pos-x.jpg',
      },
      {
        target: gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
        url: '../../resources/images/computer-history-museum/neg-x.jpg',
      },
      {
        target: gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
        url: '../../resources/images/computer-history-museum/pos-y.jpg',
      },
      {
        target: gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
        url: '../../resources/images/computer-history-museum/neg-y.jpg',
      },
      {
        target: gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
        url: '../../resources/images/computer-history-museum/pos-z.jpg',
      },
      {
        target: gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,
        url: '../../resources/images/computer-history-museum/neg-z.jpg',
      },
    ];
    faceInfos.forEach((faceInfo) => {
      const { target, url } = faceInfo;

      // Upload the canvas to the cubemap face.
      const level = 0;
      const internalFormat = gl.RGBA;
      const width = 512;
      const height = 512;
      const format = gl.RGBA;
      const type = gl.UNSIGNED_BYTE;

      // setup each face so it's immediately renderable
      gl.texImage2D(target, level, internalFormat, width, height, 0, format, type, null);

      // Asynchronously load an image
      const image = new Image();
      image.src = url;
      image.addEventListener('load', function () {
        // Now that the image has loaded make copy it to the texture.
        gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
        gl.texImage2D(target, level, internalFormat, format, type, image);
        gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
      });
    });
    gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);

    function radToDeg(r) {
      return r * 180 / Math.PI;
    }

    function degToRad(d) {
      return d * Math.PI / 180;
    }

    var fieldOfViewRadians = degToRad(60);
    var cameraYRotationRadians = degToRad(0);

    var spinCamera = true;
    // Get the starting time.
    var then = 0;

    requestAnimationFrame(drawScene);

    // Draw the scene.
    function drawScene(time) {
      // convert to seconds
      time *= 0.001;
      // Subtract the previous time from the current time
      var deltaTime = time - then;
      // Remember the current time for the next frame.
      then = time;

      webglUtils.resizeCanvasToDisplaySize(gl.canvas);

      // Tell WebGL how to convert from clip space to pixels
      gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

      gl.enable(gl.CULL_FACE);
      gl.enable(gl.DEPTH_TEST);

      // Clear the canvas AND the depth buffer.
      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

      // Compute the projection matrix
      var aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
      var projectionMatrix =
        m4.perspective(fieldOfViewRadians, aspect, 1, 2000);

      // camera going in circle 2 units from origin looking at origin
      var cameraPosition = [Math.cos(time * .1) * 2, 0, Math.sin(time * .1) * 2];
      var target = [0, 0, 0];
      var up = [0, 1, 0];
      // Compute the camera's matrix using look at.
      var cameraMatrix = m4.lookAt(cameraPosition, target, up);

      // Make a view matrix from the camera matrix.
      var viewMatrix = m4.inverse(cameraMatrix);

      // Rotate the cube around the x axis
      var worldMatrix = m4.xRotation(time * 0.11);

      // We only care about direciton so remove the translation
      var viewDirectionMatrix = m4.copy(viewMatrix);
      viewDirectionMatrix[12] = 0;
      viewDirectionMatrix[13] = 0;
      viewDirectionMatrix[14] = 0;

      var viewDirectionProjectionMatrix = m4.multiply(
        projectionMatrix, viewDirectionMatrix);
      var viewDirectionProjectionInverseMatrix =
        m4.inverse(viewDirectionProjectionMatrix);

      // draw the cube
      gl.useProgram(envmapProgramInfo.program);
      webglUtils.setBuffersAndAttributes(gl, envmapProgramInfo, cubeBufferInfo);
      webglUtils.setUniforms(envmapProgramInfo, {
        u_world: worldMatrix,
        u_view: viewMatrix,
        u_projection: projectionMatrix,
        u_texture: texture,
        u_worldCameraPosition: cameraPosition,
      });
      webglUtils.drawBufferInfo(gl, cubeBufferInfo);

      // draw the skybox
      gl.useProgram(skyboxProgramInfo.program);
      webglUtils.setBuffersAndAttributes(gl, skyboxProgramInfo, quadBufferInfo);
      webglUtils.setUniforms(skyboxProgramInfo, {
        u_viewDirectionProjectionInverse: viewDirectionProjectionInverseMatrix,
        u_skybox: texture,
      });
      webglUtils.drawBufferInfo(gl, quadBufferInfo);

      requestAnimationFrame(drawScene);
    }
  }

  main();
</script>

</html>